package me.zhengjie.rest;

import me.zhengjie.aop.log.Log;
import me.zhengjie.service.PictureService;
import me.zhengjie.service.dto.PictureQueryCriteria;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 郑杰
 * @date 2018/09/20 14:13:32
 */
@Controller
@RequestMapping("/api")
public class PictureController {

    @Autowired
    private PictureService pictureService;
    
    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Log("查询图片")
    //@PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_SELECT')")
    @GetMapping(value = "/pictures")
    @ResponseBody
    public ResponseEntity getRoles(PictureQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity(pictureService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @Log("查询图片")
    //@PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_SELECT')")
    @GetMapping(value = "/pictures/{uid:.+}")
    public void getPicEx(@PathVariable String uid,HttpServletResponse response){
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + uid);
        File file;
        FileInputStream fileIn = null;
        ServletOutputStream out = null;
        try {
            String filePath = uploadFolder+"/" + uid;
            file = new File(filePath);
            fileIn = new FileInputStream(file);
            out = response.getOutputStream();
            byte[] outputByte = new byte[1024];
            int readTmp = 0;
            while ((readTmp = fileIn.read(outputByte)) != -1) {
                out.write(outputByte, 0, readTmp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileIn.close();
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Log("查询图片")
    //@PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_SELECT')")
    @GetMapping(value = "/picture/{uid:.+}")
    public void getPic(@PathVariable String uid,HttpServletResponse response){
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + uid);   
		File file;   
	    FileInputStream fileIn = null;   
	    ServletOutputStream out = null;   
		try {
	    	String filePath = uploadFolder+"/" + uid;
	    	file = new File(filePath); 
	    	fileIn = new FileInputStream(file);   
	        out = response.getOutputStream();
	        byte[] outputByte = new byte[1024];   
	        int readTmp = 0;   
	        while ((readTmp = fileIn.read(outputByte)) != -1) {   
	           out.write(outputByte, 0, readTmp);   
	        }   
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fileIn.close();
				out.flush();   
		        out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}   
		}
    }

    /**
     * 上传图片
     * @param file
     * @return
     * @throws Exception
     */
    @Log("上传图片")
    //@PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_UPLOAD')")
    @PostMapping(value = "/pictures")
    @ResponseBody
    public ResponseEntity upload(HttpServletRequest request,@RequestParam MultipartFile file){
        String picture = pictureService.upload(file);
        Map map = new HashMap();
        map.put("errno",0);
        //map.put("id",picture.getId());
        map.put("data",new String[]{picture});
        return new ResponseEntity(map,HttpStatus.OK);
    }
    
    /**
     * 删除图片
     * @param id
     * @return
     *//*
    @Log("删除图片")
    @PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_DELETE')")
    @DeleteMapping(value = "/pictures/{id}")
    public ResponseEntity delete(@PathVariable Long id) {
        pictureService.delete(pictureService.findById(id));
        return new ResponseEntity(HttpStatus.OK);
    }*/
    
    /**
     * 删除图片
     * @param uid
     * @return
     */
    @Log("删除图片")
    //@PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_DELETE')")
    @DeleteMapping(value = "/pictures/{uid:.+}")
    @ResponseBody
    public ResponseEntity deleteByUid(@PathVariable String uid) {
		try {
			//String ap = ResourceUtils.getFile("classpath:").getAbsolutePath();
			//File f = new File(ap + "/upload/");
	    	String filePath = uploadFolder+"/" + uid;
	    	FileUtil.deleteFile(new File(filePath));
		} catch (Exception ex) {
            ex.printStackTrace();
		}
        return new ResponseEntity(HttpStatus.OK);
    }

    /**
     * 删除多张图片
     * @param ids
     * @return
     */
    @Log("删除图片")
    //@PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_DELETE')")
    @DeleteMapping(value = "/pictures")
    @ResponseBody
    public ResponseEntity deleteAll(@RequestBody Long[] ids) {
        pictureService.deleteAll(ids);
        return new ResponseEntity(HttpStatus.OK);
    }
}
